package com.gipson.amc.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.dsbj.common.msg.ResponseMessage;
import com.dsbj.starter.redis.utils.MultiRedisHelper;
import com.gipson.amc.config.annotation.RequireClientToken;
import com.gipson.amc.utils.Constants;
import io.jsonwebtoken.MalformedJwtException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class ClientTokenInteceptor extends HandlerInterceptorAdapter {

	@Autowired
	private MultiRedisHelper multiRedisHelper;

	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {

		if (handler != null && handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			RequireClientToken annotation = ((HandlerMethod) handler).getMethodAnnotation(RequireClientToken.class);
			if(annotation==null){
				annotation = handlerMethod.getMethodAnnotation(RequireClientToken.class);
			}
			if (annotation != null) {
				String clientToken = request.getHeader(Constants.HEADER_CLIENT_TOKEN_NAME);
				String appId = request.getHeader(Constants.HEADER_APPID_NAME);
				if(StringUtils.isEmpty(appId) || StringUtils.isEmpty(clientToken)){
					renderResponse(response, ResponseMessage.error(Constants.NETWORK_STATE_INVALID_ACCESS,"非法访问!"));
					return false;
				}

				String localToken =  (String) multiRedisHelper.get(Constants.CLIENT_TOKEN_PREFIX+appId,"client-token");
				if(StringUtils.isEmpty(localToken)){
					renderResponse(response, ResponseMessage.error(Constants.NETWORK_STATE_TOKEN_EXPIRED,"Token不一致,刷新客户端Token!"));
					return false;
				}
				if(!localToken.equals(clientToken)){
					renderResponse(response, ResponseMessage.error(Constants.NETWORK_STATE_TOKEN_EXPIRED,"Token不一致,刷新客户端Token!"));
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 以JSON格式输出
	 * @param response
	 */
	protected void renderResponse(HttpServletResponse response, Object responseObject) {
		//将实体对象转换为JSON Object转换
		String jsonStr = JSONObject.toJSONString(responseObject);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(jsonStr);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}

	}




	@Override
	public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
	}

}
